#!/usr/bin/python
'''
reads in files and sorts them by key, then by count.
'''
import sys
from operator import itemgetter, attrgetter


# get files.
files = []
for i in range(1, len(sys.argv)):
	files.append(sys.argv[i])
	
# read in files.
total = {}
bytype = {}
for f in files:
	# get lines and tokenize.
	fin = open(f,"rb")
	for line in fin:
		# tokenize.
		tmp = line.strip().split(" ")
		key = tmp[1]
		cnt = int(tmp[0])
		
		# add to total.
		if key not in total:
			total[key] = 0
		total[key] += cnt
		
		# add bytype.
		if f not in bytype:
			bytype[f] = {}
			
		if key not in bytype[f]:
			bytype[f][key] = 0
		bytype[f][key] += cnt
	fin.close()
	
# build total array.
pairs = []
for key in total:
	pairs.append((key, total[key]))
	
# sort by count.
pairs.sort(key=itemgetter(1))
pairs.reverse()

# print out libraries.
txt = ""
for f in files:
	txt += "%s\t" % f
#print txt

# print out values.
for p in pairs:
	key = p[0]
	txt = key + "\t"
	for f in files:
		# check if p in dict.
		if key in bytype[f]:
			val = bytype[f][key]
		else:
			val = 0
		
		# add to string.
		txt += "%i\t" % val
	
	# print line.
	print txt

	
